/*
    使用说明:

    设置开关为开的状态
    $('.js-switcher').switcher('on');

    设置开关为关的状态
    $('.js-switcher').switcher('off');

    切换开关
    $('.js-switcher').switcher('toggle');

    获取开关状态
    return:
        true 开启
        false 关闭
    $('.js-switcher').switcher('val');

    正在请求服务器，并禁用开关
    $('.js-switcher').switcher('loading');

    请求结束，取消禁用
    $('.js-switcher').switcher('reset');

 */
define(function(require) {
    'use strict';

    var $ = require('jquery'),
        disabled = 'disabled',
        className = 'ui-switcher',
        classNamePrefix = 'ui-switcher-',
        classNameOn = classNamePrefix + 'on',
        classNameOff = classNamePrefix + 'off',
        classNameDisabled = classNamePrefix + disabled,
        classNameLoading = classNamePrefix + 'loading';

    var Switcher = function(element) {
        this.$el = $(element);
        this.$el.addClass(className);
    };

    Switcher.prototype.val = function() {
        return this.$el.hasClass(classNameOn);
    };

    Switcher.prototype.setState = function(state){
        var className = classNamePrefix + state;

        this.$el
            .removeClass(classNameOn)
            .removeClass(classNameOff)
            .addClass(className);
    };

    Switcher.prototype.on = function() {
        this.setState('on');
    };

    Switcher.prototype.off = function() {
        this.setState('off');
    };

    Switcher.prototype.toggle = function(){
        this.val() ? this.off() : this.on();
    };

    Switcher.prototype.loading = function() {
        this.$el
            .addClass(classNameLoading)
            .addClass(classNameDisabled)
            .attr(disabled, disabled);
    };

    Switcher.prototype.reset = function() {
        this.$el
            .removeClass(classNameLoading)
            .removeClass(classNameDisabled)
            .removeAttr(disabled);
    };

    $.fn.switcher = function(option) {
        if(option === 'val'){
            return this.hasClass(classNameOn);
        }

        return this.each(function() {
            var $this = $(this);
            var switcher = $this.data('kdt.switcher');

            if (!switcher) {
                switcher = new Switcher($this);
                $this.data('kdt.switcher', switcher);
            }

            if(switcher[option]) {
                switcher[option]();
            } else {
                switcher.setState(option);
            }
        });
    };

    // 兼容老的switch
    $.fn['switch'] = $.fn.switcher;
});
